export default class Dragon {
  canvas;
  ctx;
  image;
  gap;
  imageData;

  constructor(container) {
    console.log('container:', container);
    this.canvas = typeof container === 'string' ? document.querySelector(container) : container;
    this.canvas.setAttribute('width', 640);
    this.canvas.setAttribute('height', 400);

    const ctx = this.canvas.getContext('2d');
    this.ctx = ctx;

    const image = new Image();
    this.image = image;
    image.src = 'assets/images/dragon.png';
    image.onload = () => {
      this.canvas.width = image.width;
      this.canvas.height = image.height;

      ctx.drawImage(image, 0, 0);

      this.genLattice();
      // TODO: 需要改成直接绘制到canvas中
      // this.genBubble();
    };
  }

  // 获取并裁剪画布的点阵信息
  genLattice(): void {
    const imageData = this.ctx.getImageData(0, 0, this.image.width, this.image.height).data;
    this.imageData = imageData;
    this.ctx.fillStyle = '#fff';
    this.ctx.fillRect(0, 0, this.image.width, this.image.height);

    const gap = 6;
    this.gap = gap;

    for (let h = 0; h < this.image.height; h += gap) {
      for (let w = 0; w < this.image.width; w += gap) {
        const position = (this.image.width * h + w) * 4;
        const r = imageData[position];
        const g = imageData[position + 1];
        const b = imageData[position + 2];

        if (r + g + b !== 0) {
          this.ctx.fillStyle = '#000';
          this.ctx.fillRect(w, h, 4, 4);
        }
      }
    }
  }

  // 通过点阵信息生成气泡dom
  genBubble(): void {
    const dragonContainer = document.getElementById('container');
    console.log('dragonContainer:', dragonContainer);
    const dragonScale = 2;

    for (let h = 0; h < this.image.height; h += this.gap) {
      for (let w = 0; w < this.image.width; w += this.gap) {
        const position = (this.image.width * h + w) * 4;
        const r = this.imageData[position];
        const g = this.imageData[position + 1];
        const b = this.imageData[position + 2];

        if (r + g + b !== 0) {
          const bubble = document.createElement('img');
          bubble.src = 'assets/images/bubble.png';
          bubble.setAttribute('class', 'bubble');

          const bubbleSize = Math.random() * 10 + 20;
          bubble.style.left = (w * dragonScale - bubbleSize / 2) + 'px';
          bubble.style.top = (h * dragonScale - bubbleSize / 2) + 'px';
          bubble.style.width = bubble.style.height = bubbleSize + 'px';
          bubble.style.animationDuration = Math.random() * 6 + 4 + 's';
          console.log('bubble~~~', bubble);

          dragonContainer.appendChild(bubble);
        }
      }
    }

  }
}
